package com.kinghood.authoritycenter.common.util;


import com.kinghood.infrastructure.model.KingHoodExceptionUtil;
import com.kinghood.authoritycenter.common.model.dto.auth.KingHoodPrincipal;
import com.kinghood.authoritycenter.common.model.dto.auth.UserDTO;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Objects;

/**
 * description
 *
 * @author zhangFanJun
 * @date 2023-12-07 23:54
 **/
public class UserUtil {

    public static KingHoodPrincipal get(){
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        Object credentials = authentication.getCredentials();
        Object principal = authentication.getPrincipal();
        if(principal instanceof KingHoodPrincipal){
            KingHoodPrincipal kingHoodPrincipal = (KingHoodPrincipal) principal;
            return kingHoodPrincipal;
        }
        return null;
    }

    public static UserDTO getUser(){
        KingHoodPrincipal kingHoodPrincipal = get();
        if(Objects.isNull(kingHoodPrincipal)){
            return null;
        }
        KingHoodExceptionUtil.isNull(kingHoodPrincipal.getAudience(),"token信息异常");
        UserDTO user = new UserDTO();
        user.setIssuer(kingHoodPrincipal.getIssuer());
        user.setId(new Long(kingHoodPrincipal.getAudience()));
        user.setUsername(kingHoodPrincipal.getSubject());

        return user;
    }

    public static Long getUserId(){
        UserDTO user = getUser();
        if(Objects.isNull(user)){
            return null;
        }
        return user.getId();
    }
}
